package com.hn.shoutchinese.pinying.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import com.hn.comm.*;
import com.hn.net.Kit;
import com.hn.shoutchinese.pinying.service.IPinyingService;

public class PinyingServiceImpl implements IPinyingService {

	private Map<String, String> pinyingMap;

	@Override
	public String getPinying(String words) {
		// String head = "http://so.diyifanwen.com/ZdSearch.asp?";
		// try {
		// word = java.net.URLEncoder.encode(word, "gb2312");
		// } catch (UnsupportedEncodingException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// String param = "KeyWords=" + word + "&Search=SWord";
		// String url = head + param;
		//
		// String content = Kit.httpRequest(url, null, "GET", "gb2312");
		//
		// String keyStart = "拼音：</span>";
		// String keyEnd = "<script>";
		// int iIndexStart = content.indexOf(keyStart) + keyStart.length();
		// int iIndexEnd = content.indexOf(keyEnd, iIndexStart);

		// String pinying = content.substring(iIndexStart, iIndexEnd);

		StringBuffer sbPinying = new StringBuffer();
		for (int i = 0; i < words.length(); i++) {
			String word = words.substring(i, i + 1);
			String pinyingWord=getPinyingMap().get(word);
			if(pinyingWord==null)
			{
				sbPinying.append(word);
			}
			else
			{
				sbPinying.append(getPinyingMap().get(word));
			}
//			if (word.equals(".")) {
//				sbPinying.append(".");
//			} else {
//				sbPinying.append(getPinyingMap().get(word));
//			}
			if (i < words.length()) {
				sbPinying.append(" ");
			}
		}
		return sbPinying.toString();
	}

	public Map<String, String> getPinyingMap() {
		// 如果拼音数据库没有加载，那么加载
		if (pinyingMap == null) {
			pinyingMap = new HashMap<String, String>();
			// D:\\eclipse_workspace\\indigo\\shoutchinese-robot\\res\\pinying.txt
			//D:\eclipse_workspace\indigo\shoutchinese-robot\res\pinying.txt
			String pinyingContent = Tools
					.readFile("D:\\eclipse_workspace\\indigo\\shoutchinese-robot\\res\\pinying.txt");

			String[] arrPinying = pinyingContent.split(",");
			for (int i = 0; i < arrPinying.length; i++) {
				String key = arrPinying[i].substring(0, 1);
				String value = arrPinying[i].substring(1,
						arrPinying[i].length());
				pinyingMap.put(key, value);
			}
		}
		return pinyingMap;

	}

}
